<?php
/**
 * Created by PhpStorm.
 * User: mabao
 * 消息：系统消息和聊天消息和聊天
 */
namespace app\api\controller;
use think\Db;
use think\Config;
class My extends Base
{
    /**
     * 异地登录验证(关于我们和注册协议在login)
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            echo json_encode(['status'=>301,'msg'=>"Token失效！请重新登录！"]);
            exit;
        }
    }
    /**
     * 点击我的获取昵称头像：备用
     * name,avatar
     */
    public function userInfo()
    {
        extract(input());
        $data = Db::table('up_u_user')->alias('u')
            ->join('up_area a1', 'u.user_sheng = a1.district_id', 'left')
            ->join('up_area a2', 'u.user_shi = a2.district_id', 'left')
            ->join('up_area a3', 'u.user_qu = a3.district_id', 'left')
            ->where('user_id', $user_id)
            ->field('u.*,a1.district sheng,a2.district shi,a3.district qu')
            ->find();
        if($data['user_signs_3']){
            $data['user_signs_3'] = explode(',',$data['user_signs_3']);
        }else{
            $data['user_signs_3'] = [];
        }
        $bg = Db::name('lunbo')
            ->where(['lb_type'=>2,'lb_status'=>1])
            ->field(['lb_id','lb_image'])
            ->order('lb_time DESC')
            ->find();
        $config = $this->getMemberConfig($user_id);
        $shengyu = array();
        $shengyu['shuaxin'] = $config['mc_fresh']-$data['user_fresh_use'];
        $shengyu['zhiding'] = $config['mc_top']-$data['user_top_use'];
        if($shengyu['shuaxin'] < 0){ $shengyu['shuaxin'] = 0; }
        if($shengyu['zhiding'] < 0){ $shengyu['zhiding'] = 0; }
        return json_encode(['status'=>200,'msg'=>$data,'bg'=>$bg,'config'=>$shengyu]);
    }
    /**
     * 修改密码
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function updatePass(){
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $old = $_POST['oldpass'];
        $new = $_POST['newpass'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code == '' || $old == '' || $new == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if($username['user_password'] != md5($old)){
            return json_encode(['status'=>3,'msg'=>'原密码输入错误']);
        }
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_password'=>md5($new),'user_token'=>$token]);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'密码修改失败']);
        }
    }
    /**
     * 更换手机号
     * @return bool
     *
     */

    public  function changePhone(){
        $oldphone = $_POST['oldphone'];
        $phone = $_POST['newphone'];
        $code = $_POST['code'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code == '' || $oldphone == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>3,'msg'=>'已经有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 301){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $res = Db::table('up_u_user')->where('user_phone',$oldphone)->update(['user_phone'=>$phone,'user_token'=>$token]);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'手机号更换失败']);
        }
    }



    /**
     * 修改头像或者昵称
     * name,avatar
     */
    public function updateUser()
    {
        extract(input());
        $update = array();
        if(isset($name) && $name) {
            $update['user_username'] = $name;
        }
        if(isset($avatar) && $avatar){
            $update['user_image'] = $avatar;
        }
        if(isset($signs) && $signs){
            $update['user_signs_3'] = trim($signs,',');
        }
        if(isset($year) && $year){
            $update['user_year_3'] = $year;
        }
        if(isset($content) && $content){
            $update['user_content_3'] = $content;
        }
        if(isset($sheng) && $sheng){
            $update['user_sheng'] = $sheng;
            $update['user_shi'] = $shi;
            $update['user_qu'] = $qu;
        }
        Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update($update);
        $username = Db::table('up_u_user')->where('user_id', $user_id)->find();
        if($username['user_signs_3']){
            $username['user_signs_3'] = explode(',',$username['user_signs_3']);
        }else{
            $username['user_signs_3'] = [];
        }
        return json_encode(['status'=>200,'msg'=>$username]);
    }

    /**
     * 我收藏的房源
     */
    public function getLikeHouse()
    {
        extract(input());
        $data = Db::table('up_like')->alias('l')
            ->join('up_house h','l.like_h_id=h.h_id','LEFT')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where('h_id','>',0)
            ->where('like_user_id',$user_id)
            ->where('h_status',1)
            ->field(['h_id','h_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','district'])
            ->order('like_id DESC')
            ->page($page,15)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我关注的经济人和设计师
     */
    public function getLikeUsers()
    {
        extract(input());
        $data = Db::table('up_like_design')->alias('l')
            ->join('up_u_user u','l.like_user_id_3=u.user_id','LEFT')
            ->where('like_user_id',$user_id)
            ->where('user_status',1)
            ->where('user_type',$type)
            ->field(['like_id','user_id','user_username','user_shop','user_image','user_phone'])
            ->order('like_id DESC')
            ->page($page,15)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我关注的经济人和设计师
     */
    public function cancelLikes()
    {
        extract(input());
        $ids = trim($ids,',');
        $res = Db::table('up_like_design')
            ->where('like_id','in',$ids)
            ->delete();
        if($res){
            return json(['status'=>200,'msg'=>'success']);
        }else{
            return json(['status'=>100,'msg'=>'取消失败，请刷新重试！']);
        }
    }
    /**
     * 我发布的房源
     */
    public function getMyHouse()
    {
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if(isset($uid) && $uid){
            $user_id = $uid;
        }
        $limit = 15;
        if(isset($num) && $num == 1){
            $limit = 3;
        }
        $where = [
            'h_user_id' => $user_id,
            'h_status' => 1,
        ];
        $where2 = [
            'h_user_id' => $user_id,
            'h_done' => 2,
        ];
        if(isset($type)){
            $where['h_type'] = $type;
            $where2['h_type'] = $type;
        }
//        $data = Db::table('up_house h')
//            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
//            ->where($where)
//            ->field(['h_id','h_title','h_hot_title','h_done','h_done_time','h_xiaoqu','h_price','h_shi','h_type','h_shis','h_tings','h_mianji','h_img','h_weis','district','h_use_top_status','h_use_fre_status','h_use_top_time','h_use_fre_time'])
//            ->order('h_time DESC')
//            ->page($page,$limit)
//            ->select();
//        如果可以看到成交的，则把where2和这个打开，上面的注释掉即可
        $data = Db::table('up_house h')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where (function ($query) use ($where){
                $query->where($where);
            })
            ->whereOr (function ($query) use ($where2){
                $query->where($where2);
            })
            ->field(['h_id','h_title','h_hot_title','h_done','h_done_time','h_xiaoqu','h_price','h_shi','h_type','h_shis','h_tings','h_mianji','h_img','h_weis','district','h_use_top_status','h_use_fre_status','h_use_top_time','h_use_fre_time'])
            ->order('h_time DESC')
            ->page($page,$limit)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我发布的案例
     */
    public function getMyCases()
    {
        extract(input());
        $data = Db::table('up_company_case')
            ->where('cc_u_id',$user_id)
            ->order('cc_time DESC')
            ->field('cc_id,cc_title,cc_name,cc_thumb')
            ->page($page,15)
            ->select();
        return json(['status'=>200,'msg'=>$data]);

    }
    /**
     * 我发布的房源之确定已完成
     */
    public function doneMyHouse()
    {
        extract(input());
        $h_ids = trim($h_ids,',');
        if(empty($h_ids)){
            return json(['status'=>100,'msg'=>'请选择房源']);
        }
        $have = Db::table('up_house')
            ->where('h_id','in',$h_ids)
            ->where('h_done',2)
            ->find();
        if($have){
            return json(['status'=>100,'msg'=>'有已成交的房源，请重新选择']);
        }
        $res = Db::table('up_house')
            ->where('h_id','in',$h_ids)
            ->update([
                'h_done' => 2,
                'h_status' => 2,
                'h_done_time' => date('Y-m-d H:i:s')
            ]);
        if($res){
            $h_ids = explode(',',$h_ids);
            foreach ($h_ids as $k => $v){
                $uid = Db::table('up_house')->where('h_id',$v)->value('h_user_id');
                //不管是谁，成交记录加一
                Db::table('up_u_user')->where('user_id',$uid)->setInc('user_chengjiao');
            }

            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>100,'msg'=>'状态更改失败，请刷新重试']);
        }
    }
    /**
     * 聊天加服务次数
     */
    public function doneChat()
    {
        extract(input());
        $res = Db::table('up_u_user')->where('user_id',$uid)->setInc('user_fuwu');
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>100,'msg'=>'error']);
        }
    }
    /**
     * 删除房源
     */
    public function deleteMyHouse()
    {
        extract(input());
        $data = Db::table('up_house')
            ->where('h_id','in',$h_id)
            ->delete();
        if($data){
            return json(['status'=>200,'msg'=>'删除成功']);
        }else{
            return json(['status'=>100,'msg'=>'删除失败']);
        }
    }
    /**
     * 我的浏览记录
     */
    public function getHistoryHouse()
    {
        extract(input());
        $data = Db::table('up_history')->alias('l')
            ->join('up_house h','l.his_h_id=h.h_id','LEFT')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where('h_id','>',0)
            ->where('his_user_id',$user_id)
            ->where('h_status',1)
            ->field(['h_id','h_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','district'])
            ->order('his_date DESC')
            ->page($page,15)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 认证前的判断：待用（看前端）
     * name,avatar
     */
    public function verifyBefore()
    {
        extract(input());
        $user = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_type,user_status,user_zheng,user_company_id_3,user_fan,user_card,user_zhizhao,user_shop,user_reject_reason')
            ->find ();
        if($user['user_type'] == 1){
            return json(['status'=>0,'msg'=>'您是普通用户，不能实名认证','user'=>$user]);
        }
        if($user['user_status'] == 0){
            return json(['status'=>0,'msg'=>'审核中','user'=>$user]);
        }
        if($user['user_status'] == 1){
            return json(['status'=>0,'msg'=>'您已认证过了','user'=>$user]);
        }
        if($user['user_status'] == 2){
            return json(['status'=>2,'msg'=>'审核未通过','user'=>$user]);
        }
        return json(['status'=>200,'msg'=>'可以实名']);
    }
    /**
     * 认证设计师获取公司
     * name,avatar
     */
    public function verifyGetComs()
    {
        extract(input());
        $where = [
            'id' => ['>',0]
        ];
        if(isset($keyword) && $keyword){
            $where['name|title'] = ['like','%'.$keyword.'%'];
        }
        $data = Db::table('up_company')
            ->where($where)
            ->order('tuijian DESC,time DESC')
            ->field('name,title,address,id')
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 认证
     * name,avatar
     */
    public function verify()
    {
        extract(input());
        $user = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_type,user_status')
            ->find ();
        if($user['user_type'] == 1){
            return json(['status'=>0,'msg'=>'您是普通用户，不能实名认证']);
        }
        if($user['user_status'] == 0){
            return json(['status'=>0,'msg'=>'审核中']);
        }
        if($user['user_status'] == 1){
            return json(['status'=>0,'msg'=>'您已认证过了']);
        }
        $update = array();
        $update['user_zheng'] = $zheng;
        $update['user_fan'] = $fan;
        $update['user_card'] = $card;
        $update['user_zhizhao'] = $zhizhao;
        $update['user_shop'] = $shop;
        $update['user_reject_time'] = date('Y-m-d H:i:s');
        $update['user_status'] = 0;
        if($user['user_type'] == 3){
            $update['user_shop'] = Db::table('up_company')->where('id',$shop)->value('name');
            $update['user_company_id_3'] = $shop;
        }
        $res = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update($update);
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }

    //-----------------充值和会员---------------------------------------
    /**
     * 充值（我的包数量和记录）
     *
     */
    public function recharge()
    {
        extract(input());
        $user = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_id,user_mytop,user_myfresh,user_auth')
            ->find ();
        $jilu =  Db::table('up_order')
            ->where('order_user_id',$user_id)
            ->where('order_status',2)
            ->where('order_type','<>',1)
            ->field(['order_date','order_type','order_money'])
            ->order('order_time DESC')
            ->page ($page,10)
            ->select ();
        return json(['status'=>200,'user'=>$user,'msg'=>$jilu]);
    }
    /**
     * 使用置顶包或者刷新包
     * type：1是使用置顶，2是使用刷新
     */
    public function useTopOrFresh()
    {
        extract(input());
        $h_d = Db::table('up_house')->where('h_id', $h_id)->field('h_status,h_done')->find();
        if($h_d['h_status'] == 2 || $h_d['h_done'] == 2){
            return json(['status'=>0,'msg'=>'已成交的房源不能再使用']);
        }
        $config = $this->getMemberConfig($user_id);
        $user = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_mytop,user_myfresh,user_top_use,user_fresh_use,user_type')
            ->find ();
        if($type == 1){
            if($user['user_mytop'] <= 0 && $config['mc_top'] <= $user['user_top_use']){
                return json(['status'=>1,'msg'=>'置顶包数量不足，请前去购买']);
            }else{

                Db::startTrans();
                try {
                    if($config['mc_top'] > $user['user_top_use']){
                        Db::table('up_u_user')->where('user_id', $user_id)->setInc('user_top_use');
                    }else{
                        Db::table('up_u_user')->where('user_id', $user_id)->setDec('user_mytop');
                    }
                    $data = array();
                    $data['top_h_id'] = $h_id;
                    $data['top_type'] = $h_type;
                    $data['top_time'] = date('Y-m-d H:i:s');
                    $data['top_updatetime'] = date('Y-m-d H:i:s');
                    $data['top_updatetime2'] = date('Y-m-d H:i:s');
                    $data['top_shi'] = $h_shi;
                    Db::table('up_top')->where('user_id', $user_id)->insert($data);
                    Db::table('up_house')->where('h_id', $h_id)
                        ->update(['h_use_top_status'=>2,'h_use_top_time'=>date('Y-m-d H:i:s')]);
                    //PS：如果是经纪人 改一下房源表的list时间和order-----start
                    if($user['user_type'] == 2){
                        Db::table('up_house')->where('h_id', $h_id)
                            ->update(['h_listtime'=>date('Y-m-d H:i:s'),'h_order'=>2]);
                        $this->updateHouseList($h_type,$h_shi);
                    }
                    //PS：如果是经纪人 改一下房源表的list时间和order----- end
                    Db::commit();
                    return json(['status'=>200,'msg'=>'OK']);
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
                }
            }
        }else{
            if($user['user_myfresh'] <= 0 && $config['mc_fresh'] <= $user['user_fresh_use']){
                return json(['status'=>1,'msg'=>'刷新包数量不足，请前去购买']);
            }else{

                Db::startTrans();
                try {
                    if($config['mc_fresh'] > $user['user_fresh_use']){
                        Db::table('up_u_user')->where('user_id', $user_id)->setInc('user_fresh_use');
                    }else{
                        Db::table('up_u_user')->where('user_id', $user_id)->setDec('user_myfresh');
                    }
                    $data = array();
                    $data['h_time'] = date('Y-m-d H:i:s');
                    $data['h_listtime'] = date('Y-m-d H:i:s');
                    $data['h_use_fre_status'] = 2;
                    $data['h_use_fre_time'] = date('Y-m-d H:i:s');
                    Db::table('up_house')->where('h_id', $h_id)->update($data);
                    Db::commit();
                    return json(['status'=>200,'msg'=>'OK']);
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
                }
            }
        }
    }
    //-----------------充值和会员---------------------------------------
    /**
     * 客服
     */
    public function kefu()
    {
        extract(input());
        $data = [
            'k_user_id'=>$user_id,
            'k_title'=>$title,
            'k_desc'=>$desc,
            'k_time'=>date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_kefu')->insert($data);
        if($res){
            return json(['status'=>200,'msg'=>'提交成功']);
        }else{
            return json(['status'=>0,'msg'=>'提交失败']);
        }
    }
}